// src/stores/universalVisualizerSettingsStore.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
// Import the default color from config
import { defaultElementObjectColor } from '@/config';
import { PanelPosition } from '@vue-flow/core';
// REMOVE import from non-existent types file
// import type { ColoringMode, AttributeDisplayMode, AttributeSeparatorStyle, NodeRenderingMethod, DagreAlign, DagreRanker, HandlePositionMode, XmlTagNameDisplayMode, XmlParserType, ScriptParserEngine } from './universalVisualizerSettingsStoreTypes';

// --- MOVE TYPE DEFINITIONS HERE ---
// Define the possible coloring modes
export type ColoringMode =
  | 'single-structure' | 'single-true' | 'level' | 'semantic' | 'jdf-keyword'
  | 'jdf-keyword-level' | 'metron-keyword' | 'metron-keyword-level' | 'custom-schema' | 'jdf';

// Type for Attribute Display Mode
export type AttributeDisplayMode = 'hide' | 'count' | 'first-1' | 'first-3' | 'all';

// Type for separator style
export type AttributeSeparatorStyle = 'none' | 'dashed' | 'solid' | 'dotted';

// Type for rendering method
export type NodeRenderingMethod = 'template' | 'renderFunction';

// Dagre-specific types
export type DagreAlign = 'UL' | 'UR' | 'DL' | 'DR' | 'C' | undefined;
export type DagreRanker = 'network-simplex' | 'tight-tree' | 'longest-path';

// Handle Position Mode type
export type HandlePositionMode = 'auto' | 'top-bottom' | 'left-right';

// XML Tag Name Display Mode Type
export type XmlTagNameDisplayMode = 'nameOnly' | 'openingTag' | 'closingTag';

// XML Parser Type Export
export type XmlParserType = 'dom' | 'fast-xml' | 'libxml2';

// Script Parser Engine Type
export type ScriptParserEngine = 'swc' | 'babel';

// Rename the store ID and exported function
export const useUniversalVisualizerSettingsStore = defineStore('universal-visualizer-settings', () => {
    // --- State ---
    // Set default to the JDF + Level mode
    const coloringMode = ref<ColoringMode>('jdf-keyword-level');
    // Rename state for single structure mode
    const singleStructureColorValue = ref<string>('#a7f3d0'); // Default: Light Emerald
    // ADD state for the true single color mode (different default? maybe slightly darker grey)
    const trueSingleColorValue = ref<string>('#d1d5db'); // Default: Light Gray
    // ADD state for attribute display mode
    const attributeDisplayMode = ref<AttributeDisplayMode>('all');
    // Add the new state for separator style
    const attributeSeparatorStyle = ref<AttributeSeparatorStyle>('dashed'); // Default to dashed
    // NEW: State for normalizing appearance
    const normalizeAppearanceWithAttrs = ref<boolean>(true); // Default to true
    // NEW: State for rendering method
    const nodeRenderingMethod = ref<NodeRenderingMethod>('template'); // Default to template
    const nodeColoringMode = ref<ColoringMode>('semantic');
    const layoutDirection = ref<'TB' | 'LR'>('TB');
    const nodeSpacing = ref<number>(60); // Adjusted default
    const layerSpacing = ref<number>(80); // Adjusted default
    const showMiniMap = ref<boolean>(true);
    const showControls = ref<boolean>(true);
    const showBackground = ref<boolean>(true);
    const controlsPosition = ref<PanelPosition>(PanelPosition.BottomLeft);
    const controlsShowZoom = ref<boolean>(true);
    const controlsShowFitView = ref<boolean>(true);
    const controlsShowInteractive = ref<boolean>(true);
    const controlsShowRedoLayout = ref<boolean>(true);
    const controlsShowToggleOrientation = ref<boolean>(true);
    // --- NEW Dagre Layout State ---
    const dagreAlign = ref<DagreAlign>(undefined); // Default alignment
    const dagreRanker = ref<DagreRanker>('network-simplex'); // Default ranker
    // --- NEW Handle Position Mode State ---
    const handlePositionMode = ref<HandlePositionMode>('auto'); // Default to auto
    // --- NEW XML Tag Name Display Mode State ---
    const xmlTagNameDisplayMode = ref<XmlTagNameDisplayMode>('nameOnly');
    // --- NEW: State for XML parser selection ---
    const selectedXmlParser = ref<XmlParserType>('dom'); // Default to DOMParser
    // --- NEW: State for Realtime XML Validation ---
    const enableRealtimeXmlValidation = ref<boolean>(true); // Default to enabled
    // --- ADD: State for Word Wrap ---
    const wordWrap = ref<boolean>(true); // Default word wrap to enabled
    // --- NEW: State for Automatic QuickJS Evaluation ---
    const enableAutomaticQuickJs = ref<boolean>(true); // Default to enabled
    // --- NEW: State for Script Parser Engine ---
    const scriptParserEngine = ref<ScriptParserEngine>('swc'); // Default to SWC
    // --- NEW: QuickJS Runtime Limits --- 
    const quickJsMemoryLimitMb = ref<number>(10); // Default: 10 MB (For full script)
    const quickJsStackSizeKb = ref<number>(512); // Default: 512 KB (For full script)
    // --- NEW: Limits for evaluateExpression --- 
    const quickJsExpressionMemoryLimitMb = ref<number>(2); // Default: 2 MB (For single expressions)
    const quickJsExpressionStackSizeKb = ref<number>(128); // Default: 128 KB (For single expressions)
    // --- ADD NEW State Properties --- 
    const quickJsExprMemoryLimitMb = ref<number>(2);   // NEW default for expression evaluation (e.g., 2MB)
    const quickJsExprStackSizeKb = ref<number>(128);   // NEW default for expression evaluation (e.g., 128KB)
    const richDisplayItemLimit = ref<number>(10);
    const richDisplayMaxDepth = ref<number>(5);

    // --- Actions ---
    const setColoringMode = (mode: ColoringMode) => {
        const validModes: ColoringMode[] = [
            'single-structure', 'single-true',
            'level', 'semantic',
            'jdf-keyword', 'jdf-keyword-level',
            'metron-keyword', 'metron-keyword-level',
            'custom-schema', 'jdf'
        ];
        if (validModes.includes(mode)) {
            coloringMode.value = mode;
        } else {
            console.warn(`Invalid coloring mode: ${mode}`);
        }
    };

    // Rename action for single structure color
    const setSingleStructureColorValue = (color: string) => {
        // Remove the check for starting with '#'
        if (typeof color === 'string') { 
            singleStructureColorValue.value = color;
        }
    };

    // ADD action to set the true single color
    const setTrueSingleColorValue = (color: string) => {
        // Remove the check for starting with '#'
        // Accept any string value from the color picker
        if (typeof color === 'string') { 
            trueSingleColorValue.value = color;
        }
    };

    // ADD action to set attribute display mode
    const setAttributeDisplayMode = (mode: AttributeDisplayMode) => {
        const validModes: AttributeDisplayMode[] = ['hide', 'count', 'first-1', 'first-3', 'all'];
        if (validModes.includes(mode)) {
            attributeDisplayMode.value = mode;
        }
    };

    // Action to set the separator style
    const setAttributeSeparatorStyle = (style: AttributeSeparatorStyle) => {
        attributeSeparatorStyle.value = style;
    };

    // NEW: Action to toggle normalize appearance
    function toggleNormalizeAppearance() {
        normalizeAppearanceWithAttrs.value = !normalizeAppearanceWithAttrs.value;
    }

    // NEW: Action to set rendering method
    function setNodeRenderingMethod(method: NodeRenderingMethod) {
        nodeRenderingMethod.value = method;
    }

    const setNormalizeAppearance = (normalize: boolean) => {
        normalizeAppearanceWithAttrs.value = normalize;
    };

    const setNodeColoringMode = (mode: ColoringMode) => {
        nodeColoringMode.value = mode;
    };

    const setLayoutDirection = (direction: 'TB' | 'LR') => {
        layoutDirection.value = direction;
    };

    const setNodeSpacing = (spacing: number) => {
        nodeSpacing.value = spacing;
    };

    const setLayerSpacing = (spacing: number) => {
        layerSpacing.value = spacing;
    };

    const setShowMiniMap = (show: boolean) => {
        showMiniMap.value = show;
    };

    const setShowControls = (show: boolean) => {
        showControls.value = show;
    };

    const setShowBackground = (show: boolean) => {
        showBackground.value = show;
    };

    const setControlsPosition = (position: PanelPosition) => {
        controlsPosition.value = position;
    };

    const setControlsShowZoom = (show: boolean) => {
        controlsShowZoom.value = show;
    };

    const setControlsShowFitView = (show: boolean) => {
        controlsShowFitView.value = show;
    };

    const setControlsShowInteractive = (show: boolean) => {
        controlsShowInteractive.value = show;
    };

    const setControlsShowRedoLayout = (show: boolean) => {
        controlsShowRedoLayout.value = show;
    };

    const setControlsShowToggleOrientation = (show: boolean) => {
        controlsShowToggleOrientation.value = show;
    };

    // --- NEW Dagre Layout Actions ---
    const setDagreAlign = (align: DagreAlign) => {
        dagreAlign.value = align;
    };

    const setDagreRanker = (ranker: DagreRanker) => {
        dagreRanker.value = ranker;
    };

    // --- NEW Handle Position Mode Action ---
    const setHandlePositionMode = (mode: HandlePositionMode) => {
        handlePositionMode.value = mode;
    };

    // --- NEW XML Tag Name Display Mode Action ---
    const setXmlTagNameDisplayMode = (mode: XmlTagNameDisplayMode) => {
        const validModes: XmlTagNameDisplayMode[] = ['nameOnly', 'openingTag', 'closingTag'];
        if (validModes.includes(mode)) {
            xmlTagNameDisplayMode.value = mode;
        } else {
            console.warn(`Invalid XML tag name display mode: ${mode}`);
        }
    };

    // --- NEW: Action to set XML parser ---
    const setSelectedXmlParser = (parser: XmlParserType) => {
        const validParsers: XmlParserType[] = ['dom', 'fast-xml', 'libxml2'];
        if (validParsers.includes(parser)) {
            selectedXmlParser.value = parser;
        } else {
            console.warn(`Invalid XML parser selected: ${parser}`);
        }
    };

    // --- NEW: Action for Realtime XML Validation ---
    const setEnableRealtimeXmlValidation = (enable: boolean) => {
        enableRealtimeXmlValidation.value = enable;
    };

    // --- ADD: Action for Word Wrap ---
    const setWordWrap = (enable: boolean) => {
        wordWrap.value = enable;
    };

    // --- NEW: Action for Automatic QuickJS ---
    const setEnableAutomaticQuickJs = (enable: boolean) => {
        enableAutomaticQuickJs.value = enable;
    };

    // --- NEW: Action for Script Parser Engine ---
    const setScriptParserEngine = (engine: ScriptParserEngine) => {
        const validEngines: ScriptParserEngine[] = ['swc', 'babel'];
        if (validEngines.includes(engine)) {
            scriptParserEngine.value = engine;
        } else {
            console.warn(`Invalid script parser engine: ${engine}`);
        }
    };

    // --- NEW: Actions for QuickJS Limits --- 
    const setQuickJsMemoryLimitMb = (limit: number) => {
        // Add basic validation if needed (e.g., minimum limit)
        if (typeof limit === 'number' && limit >= 1) { 
            quickJsMemoryLimitMb.value = Math.round(limit);
        }
    };
    const setQuickJsStackSizeKb = (limit: number) => {
        // Add basic validation if needed
        if (typeof limit === 'number' && limit >= 64) { // Example minimum 64KB
            quickJsStackSizeKb.value = Math.round(limit);
        }
    };

    // --- NEW: Actions for Expression Limits --- 
    const setQuickJsExpressionMemoryLimitMb = (limit: number) => {
        // Add basic validation if needed (e.g., minimum limit 1MB)
        if (typeof limit === 'number' && limit >= 1) { 
            quickJsExpressionMemoryLimitMb.value = Math.round(limit); // Ensure integer
        }
    };
    const setQuickJsExpressionStackSizeKb = (limit: number) => {
        // Add basic validation if needed (e.g., minimum limit 32KB)
        if (typeof limit === 'number' && limit >= 32) { 
            quickJsExpressionStackSizeKb.value = Math.round(limit);
        }
    };

    // --- ADD NEW Actions for Expression Limits --- 
    const setQuickJsExprMemoryLimitMb = (limit: number) => {
        // Add basic validation if needed (e.g., minimum limit 1MB)
        if (typeof limit === 'number' && limit >= 1) { 
            quickJsExprMemoryLimitMb.value = Math.round(limit); // Basic validation
        }
    };
    const setQuickJsExprStackSizeKb = (size: number) => {
        // Add basic validation if needed (e.g., minimum limit 32KB)
        if (typeof size === 'number' && size >= 32) { 
            quickJsExprStackSizeKb.value = Math.round(size);
        }
    };

    const setRichDisplayItemLimit = (limit: number) => {
        if (typeof limit === 'number' && limit >= 1) {
            richDisplayItemLimit.value = Math.round(limit);
        }
    };

    const setRichDisplayMaxDepth = (depth: number) => {
        if (typeof depth === 'number' && depth >= 1) {
            richDisplayMaxDepth.value = Math.round(depth);
        }
    };

    // ADD setter actions for layout properties
    return {
        // State
        coloringMode,
        singleStructureColorValue,
        trueSingleColorValue,
        attributeDisplayMode,
        attributeSeparatorStyle,
        normalizeAppearanceWithAttrs,
        nodeRenderingMethod,
        nodeColoringMode,
        layoutDirection,
        nodeSpacing,
        layerSpacing,
        dagreAlign,
        dagreRanker,
        handlePositionMode,
        xmlTagNameDisplayMode,
        selectedXmlParser,
        enableRealtimeXmlValidation,
        wordWrap,
        enableAutomaticQuickJs,
        scriptParserEngine,
        showMiniMap,
        showControls,
        showBackground,
        controlsPosition,
        controlsShowZoom,
        controlsShowFitView,
        controlsShowInteractive,
        controlsShowRedoLayout,
        controlsShowToggleOrientation,
        quickJsMemoryLimitMb,
        quickJsStackSizeKb,
        quickJsExpressionMemoryLimitMb,
        quickJsExpressionStackSizeKb,
        quickJsExprMemoryLimitMb,
        quickJsExprStackSizeKb,
        richDisplayItemLimit,
        richDisplayMaxDepth,
        // Actions
        setColoringMode,
        setSingleStructureColorValue,
        setTrueSingleColorValue,
        setAttributeDisplayMode,
        setAttributeSeparatorStyle,
        toggleNormalizeAppearance,
        setNodeRenderingMethod,
        setNormalizeAppearance,
        setNodeColoringMode,
        setLayoutDirection,
        setNodeSpacing,
        setLayerSpacing,
        setShowMiniMap,
        setShowControls,
        setShowBackground,
        setControlsPosition,
        setControlsShowZoom,
        setControlsShowFitView,
        setControlsShowInteractive,
        setControlsShowRedoLayout,
        setControlsShowToggleOrientation,
        setDagreAlign,
        setDagreRanker,
        setHandlePositionMode,
        setXmlTagNameDisplayMode,
        setSelectedXmlParser,
        setEnableRealtimeXmlValidation,
        setWordWrap,
        setEnableAutomaticQuickJs,
        setScriptParserEngine,
        setQuickJsMemoryLimitMb,
        setQuickJsStackSizeKb,
        setQuickJsExpressionMemoryLimitMb,
        setQuickJsExpressionStackSizeKb,
        setQuickJsExprMemoryLimitMb,
        setQuickJsExprStackSizeKb,
        setRichDisplayItemLimit,
        setRichDisplayMaxDepth,
    };
}, {
    // --- Corrected Persist Config --- 
    persist: {
        key: 'jdfsight-universal-visualizer-settings',
        // storage: localStorage, // Default is localStorage, can be omitted
        // `paths` should be directly under persist
        paths: [
            'coloringMode',
            'singleStructureColorValue',
            'trueSingleColorValue',
            'attributeDisplayMode',
            'attributeSeparatorStyle',
            'normalizeAppearanceWithAttrs',
            'nodeRenderingMethod',
            'layoutDirection',
            'nodeSpacing',
            'layerSpacing',
            'dagreAlign',
            'dagreRanker',
            'handlePositionMode',
            'xmlTagNameDisplayMode',
            'selectedXmlParser',
            'enableRealtimeXmlValidation',
            'wordWrap',
            'enableAutomaticQuickJs',
            'scriptParserEngine',
            'showMiniMap',
            'showControls',
            'showBackground',
            'controlsPosition',
            'controlsShowZoom',
            'controlsShowFitView',
            'controlsShowInteractive',
            'controlsShowRedoLayout',
            'controlsShowToggleOrientation',
            'quickJsMemoryLimitMb',
            'quickJsStackSizeKb',
            'quickJsExpressionMemoryLimitMb',
            'quickJsExpressionStackSizeKb',
            'quickJsExprMemoryLimitMb',
            'quickJsExprStackSizeKb',
            'richDisplayItemLimit',
            'richDisplayMaxDepth',
        ],
        // debug: import.meta.env.DEV, // Debug option might not be standard
    }
});
